package com.shb.jutils.commons;

import java.time.Duration;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author shenb
 * @date 2023-03-07 14:25
 */
public class DurationUtil {

    /**
     * 将数字字符串转成Duration对象， 支持以下单位：ns：纳秒, ms：毫秒, s：秒, m：分钟, h：小时, d：天
     * <br>
     * 没有单位时，默认为毫秒。空字符串默认表示0持续时间
     * @param text
     * @return
     */
    public static Duration parseDuration(String text) {
        text = text.toLowerCase(Locale.ROOT)
                .trim();
        if (text.isEmpty()) {
            return Duration.ZERO;
        }
        Pattern p = Pattern.compile("(\\d+)([a-zA-Z]*)");
        Matcher matcher = p.matcher(text);
        if (matcher.find()) {
            int num = Integer.parseInt(matcher.group(1));
            String unit = matcher.group(2);

            switch (unit) {
                case "ns":
                    return Duration.ofNanos(num);
                case "":
                    return Duration.ofMillis(num);
                case "ms":
                    return Duration.ofMillis(num);
                case "s":
                    return Duration.ofSeconds(num);
                case "m":
                    return Duration.ofMinutes(num);
                case "h":
                    return Duration.ofHours(num);
                case "d":
                    return Duration.ofDays(num);
                default:
                    throw new IllegalArgumentException("Can not parse duration: " + text);
            }
        }
        throw new IllegalArgumentException("Can not parse duration: " + text);
    }

}
